package com.hm.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author 文希
 * @create 2019-06-19 9:19
 **/
public class JDBCTools {
    /**
     * 获取连接
     * @return {@link Connection}
     * @throws IOException io异常
     * @throws ClassNotFoundException 类字节码找不到异常
     * @throws SQLException sql异常
     */
    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        String driverClass = null;
        String jdbcUrl = null;
        String user = null;
        String password = null;

        InputStream in = JDBCTools.class.getResourceAsStream("/jdbc.properties");
        Properties properties = new Properties();
        properties.load(in);

        driverClass = properties.getProperty("driver");
        jdbcUrl = properties.getProperty("url");
        user = properties.getProperty("user");
        password = properties.getProperty("password");

        Class.forName(driverClass);
        return DriverManager.getConnection(jdbcUrl, user, password);
    }

    public static void release(ResultSet resultSet, Statement statement,Connection connection){
        if (null != statement){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != resultSet){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
